<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%
  // 模拟数据库 - 实际项目中应使用真实数据库
  Map<String, String> userDatabase = (Map<String, String>)application.getAttribute("userDatabase");
  if(userDatabase == null) {
    userDatabase = new HashMap<>();
    // 添加一个默认管理员账户
    userDatabase.put("admin", "123456");
    application.setAttribute("userDatabase", userDatabase);
  }

  // 获取表单数据
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  String confirmPassword = request.getParameter("confirmPassword");
  String email = request.getParameter("email");

  // 验证数据
  if(username == null || username.trim().isEmpty()) {
    request.setAttribute("msg", "用户名不能为空！");
    request.getRequestDispatcher("register.jsp").forward(request, response);
    return;
  }

  if(password == null || password.trim().isEmpty()) {
    request.setAttribute("msg", "密码不能为空！");
    request.getRequestDispatcher("register.jsp").forward(request, response);
    return;
  }

  if(!password.equals(confirmPassword)) {
    request.setAttribute("msg", "两次输入的密码不一致！");
    request.getRequestDispatcher("register.jsp").forward(request, response);
    return;
  }

  if(email == null || email.trim().isEmpty()) {
    request.setAttribute("msg", "邮箱不能为空！");
    request.getRequestDispatcher("register.jsp").forward(request, response);
    return;
  }

  // 检查用户名是否已存在
  if(userDatabase.containsKey(username)) {
    request.setAttribute("msg", "用户名已存在，请选择其他用户名！");
    request.getRequestDispatcher("register.jsp").forward(request, response);
    return;
  }

  // 注册新用户
  userDatabase.put(username, password);
  application.setAttribute("userDatabase", userDatabase);

  // 注册成功后直接登录
  session.setAttribute("username", username);

  // 增加当前在线用户数
  Integer currentUsers = (Integer)application.getAttribute("currentUsers");
  if(currentUsers == null) {
    currentUsers = 0;
  }
  application.setAttribute("currentUsers", currentUsers + 1);

  // 重定向到首页
  response.sendRedirect("index.jsp");
%>